package com.qst.service.impl;

import com.qst.pojo.entity.SystemSettings;
import com.qst.pojo.entity.User;
import com.qst.repository.SystemSettingsRepository;
import com.qst.repository.UserRepository;
import com.qst.service.EmailService;
import jakarta.mail.internet.MimeMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.stream.Collectors;

/**
 * 邮件服务实现类
 */
@Service
public class EmailServiceImpl implements EmailService {

    private static final Logger logger = LoggerFactory.getLogger(EmailServiceImpl.class);

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private SystemSettingsRepository settingsRepository;

    @Value("${spring.mail.username}")
    private String fromEmail;

    @Override
    public void sendSimpleEmail(String to, String subject, String content) {
        try {
            // 检查邮件通知是否启用
            Optional<SystemSettings> enabledSetting = settingsRepository.findBySettingKey("email.enabled");
            boolean isEnabled = enabledSetting.map(s -> Boolean.parseBoolean(s.getSettingValue())).orElse(false);
            
            if (!isEnabled) {
                logger.warn("邮件通知未启用，跳过发送到: {}", to);
                return;
            }
            
            // 从数据库获取邮件配置
            JavaMailSenderImpl dynamicMailSender = createMailSenderFromSettings();
            String configuredFromEmail = getSettingValue("email.fromEmail", fromEmail);
            String configuredFromName = getSettingValue("email.fromName", "资源回收管理平台");
            
            // 使用MimeMessage代替SimpleMessage以支持更多功能
            MimeMessage message = dynamicMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            
            // 设置发件人（带名称）
            helper.setFrom(configuredFromEmail, configuredFromName);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, false);
            
            // 设置邮件头，提高送达率
            message.setHeader("X-Priority", "3");
            message.setHeader("X-Mailer", "Resource Recycling Platform");
            
            dynamicMailSender.send(message);
        } catch (Exception e) {
            logger.error("简单邮件发送失败到: {}", to, e);
            // 不抛出异常，避免影响业务流程
            logger.warn("邮件发送失败，但不影响业务继续执行");
        }
    }

    @Override
    public void sendHtmlEmail(String to, String subject, String content) {
        try {
            // 检查邮件通知是否启用
            Optional<SystemSettings> enabledSetting = settingsRepository.findBySettingKey("email.enabled");
            boolean isEnabled = enabledSetting.map(s -> Boolean.parseBoolean(s.getSettingValue())).orElse(false);
            
            if (!isEnabled) {
                logger.warn("邮件通知未启用，跳过发送到: {}", to);
                return;
            }
            
            // 从数据库获取邮件配置
            JavaMailSenderImpl dynamicMailSender = createMailSenderFromSettings();
            String configuredFromEmail = getSettingValue("email.fromEmail", fromEmail);
            String configuredFromName = getSettingValue("email.fromName", "资源回收管理平台");
            
            MimeMessage message = dynamicMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            
            // 设置发件人（带名称）
            helper.setFrom(configuredFromEmail, configuredFromName);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            
            // 设置邮件头，提高送达率
            message.setHeader("X-Priority", "3");
            message.setHeader("X-Mailer", "Resource Recycling Platform");
            
            dynamicMailSender.send(message);
        } catch (Exception e) {
            logger.error("HTML邮件发送失败到: {}", to, e);
            // 不抛出异常，避免影响业务流程
            logger.warn("邮件发送失败，但不影响业务继续执行");
        }
    }

    @Override
    public boolean testEmailSettings(Map<String, Object> emailSettings) {
        try {
            // 创建临时的邮件发送器用于测试
            JavaMailSenderImpl testSender = new JavaMailSenderImpl();
            
            // 设置SMTP服务器
            String host = (String) emailSettings.get("smtpHost");
            testSender.setHost(host);
            
            // 设置端口
            Integer port = (Integer) emailSettings.get("smtpPort");
            testSender.setPort(port != null ? port : 587);
            
            // 设置用户名和密码
            String username = (String) emailSettings.get("fromEmail");
            String password = (String) emailSettings.get("password");
            testSender.setUsername(username);
            testSender.setPassword(password);
            
            // 设置编码
            testSender.setDefaultEncoding("UTF-8");
            
            // 设置邮件属性
            Properties props = testSender.getJavaMailProperties();
            props.put("mail.smtp.auth", "true");
            props.put("mail.debug", "true"); // 开启调试模式
            
            // 根据加密方式设置属性
            String encryption = (String) emailSettings.get("encryption");
            
            if ("ssl".equalsIgnoreCase(encryption)) {
                props.put("mail.smtp.ssl.enable", "true");
                props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                props.put("mail.smtp.socketFactory.port", port);
                props.put("mail.smtp.socketFactory.fallback", "false");
            } else if ("tls".equalsIgnoreCase(encryption)) {
                props.put("mail.smtp.starttls.enable", "true");
                props.put("mail.smtp.starttls.required", "true");
            }
            
            props.put("mail.smtp.connectiontimeout", "10000");
            props.put("mail.smtp.timeout", "10000");
            props.put("mail.smtp.writetimeout", "10000");
            
            // 查询所有用户的邮箱（排除空邮箱和管理员）
            List<User> users = userRepository.findAll();
            List<String> emails = users.stream()
                    .filter(user -> user.getEmail() != null && !user.getEmail().isEmpty())
                    .filter(user -> user.getRole() != User.UserRole.admin) // 不发送给管理员
                    .map(User::getEmail)
                    .distinct() // 去重
                    .collect(Collectors.toList());
            
            if (emails.isEmpty()) {
                logger.warn("没有找到可发送测试邮件的用户邮箱");
                throw new RuntimeException("没有找到可发送测试邮件的用户邮箱");
            }
            
            // 发送测试邮件给所有用户
            int successCount = 0;
            int failCount = 0;
            
            for (String email : emails) {
                try {
                    SimpleMailMessage message = new SimpleMailMessage();
                    message.setFrom(username);
                    message.setTo(email);
                    message.setSubject("【资源回收管理平台】邮件配置测试");
                    message.setText("尊敬的用户：\n\n" +
                            "这是一封来自资源回收管理平台的测试邮件。\n" +
                            "如果您收到此邮件，说明邮件服务配置成功！\n\n" +
                            "今后您将通过邮件接收平台的重要通知。\n\n" +
                            "感谢您的支持！\n\n" +
                            "资源回收管理平台\n" +
                            java.time.LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    
                    testSender.send(message);
                    successCount++;
                } catch (Exception e) {
                    failCount++;
                    logger.error("测试邮件发送失败到: {}, 错误: {}", email, e.getMessage());
                }
            }
            
            if (successCount == 0) {
                throw new RuntimeException("所有测试邮件发送失败");
            }
            
            return true;
            
        } catch (Exception e) {
            logger.error("测试邮件发送失败，详细错误信息：", e);
            String errorMsg = e.getMessage();
            if (e.getCause() != null) {
                errorMsg = e.getCause().getMessage();
            }
            throw new RuntimeException("邮件测试失败：" + errorMsg);
        }
    }

    /**
     * 从数据库配置创建邮件发送器
     */
    private JavaMailSenderImpl createMailSenderFromSettings() {
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        
        // 从数据库读取配置
        String host = getSettingValue("email.smtpHost", "smtp.qq.com");
        int port = Integer.parseInt(getSettingValue("email.smtpPort", "587"));
        String username = getSettingValue("email.fromEmail", "");
        String password = getSettingValue("email.password", "");
        String encryption = getSettingValue("email.encryption", "tls");
        
        mailSender.setHost(host);
        mailSender.setPort(port);
        mailSender.setUsername(username);
        mailSender.setPassword(password);
        mailSender.setDefaultEncoding("UTF-8");
        
        // 设置邮件属性
        Properties props = mailSender.getJavaMailProperties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.connectiontimeout", "10000");
        props.put("mail.smtp.timeout", "10000");
        props.put("mail.smtp.writetimeout", "10000");
        
        // 根据加密方式设置属性
        if ("ssl".equalsIgnoreCase(encryption)) {
            props.put("mail.smtp.ssl.enable", "true");
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.socketFactory.port", String.valueOf(port));
            props.put("mail.smtp.socketFactory.fallback", "false");
        } else if ("tls".equalsIgnoreCase(encryption)) {
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.starttls.required", "true");
        }
        
        return mailSender;
    }

    /**
     * 从数据库获取配置值
     */
    private String getSettingValue(String key, String defaultValue) {
        Optional<SystemSettings> setting = settingsRepository.findBySettingKey(key);
        return setting.map(SystemSettings::getSettingValue).orElse(defaultValue);
    }
}

